<template>
  <div class="category">
    <!-- 左侧主分类 -->
    <van-sidebar v-model="activeKey">
      <van-sidebar-item
        v-for="category in categories"
        :key="category.id"
        :title="category.name"
        @click="findSubCategories(category.id)"
      />
    </van-sidebar>
    <!-- 右侧子分类 -->
    <div style="flex: 1;">
      <!-- 利用宫格显示子分类 -->
      <van-grid
        column-num="3"
        gutter="6"
      >
        <van-grid-item
          v-for="sub in subCategories"
          :key="sub.id"
          :icon="sub.imageUrl"
          :text="sub.title"
        />
      </van-grid>
    </div>
  </div>
</template>

<script>
import { getCategories, getSubCategories } from '../../api/category'
export default {
  name: 'Category',
  data() {
    return {
      activeKey: 0,
      categories: [], // 所有主分类
      subCategories: [], // 子分类数组
    }
  },
  created() {
    /* 查询主分类数据 */
    getCategories()
      .then(data => {
        console.log(data)
        // 将查询到的主分类数据保存起来
        this.categories = data.list.slice(1)
        // 默认查询第一项的子分类
        this.findSubCategories(this.categories[0].id)
      })
      .catch(error => console.error('异常：', error))
  },
  methods: {
    findSubCategories(id) {
      getSubCategories(id)
        .then(data => {
          console.log('子分类：', data)
          this.subCategories = data.categories
        })
        .catch(error => console.error('异常：', error))
    },
  },
}
</script>

<style lang="less" scoped>
  .category {
    display: flex;
  }
</style>
